﻿using ClosedXML.Excel;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyMES.Domain.W.Liststructure;
using MyMES.Domain.zmc;
using MyMES.Domain.zyy;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Writer.API.Application.Commends.Works;

namespace MyMES.Writer.API.Controllers.Works
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WorksController : ControllerBase
    {
        private readonly IMediator med;
        private readonly IBaseRepository<WorkOrder> works;

        /// <summary>
        /// 生产工单
        /// </summary>
        /// <param name="med"></param>
        /// <param name="works"></param>
        public WorksController(IMediator med,IBaseRepository<WorkOrder> works)
        {
            this.med = med;
            this.works = works;
        }
        /// <summary>
        /// 添加生产工单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<WorkOrder>> AddWorkds(AddWorksCommands request, CancellationToken cancellationToken)
        {
            try
            {
                return await med.Send(request, cancellationToken);
            }
            catch (Exception)
            {

                throw;
            }
            
        }
        /// <summary>
        /// 删除生产工单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<APIResult<WorkOrder>> DeleteWorks(DeleteWorksCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await med.Send(request, cancellationToken);
            }
            catch (Exception)
            {

                throw;
            }
           
        }
        /// <summary>
        /// 更新生产工单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<APIResult<WorkOrder>> UpdateWorks(UpdateWorksCommand request, CancellationToken cancellationToken)
        {
            try
            {
                return await med.Send(request, cancellationToken);
            }
            catch (Exception)
            {

                throw;
            }
          
        }
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportInventories(IFormFile file)
        {
            APIResult<int> result = new APIResult<int>();
            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = APIEnum.查询失败;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    result.Code = APIEnum.查询失败;
                    result.Msg = "仅支持上传 Excel 文件";
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var workbook = new XLWorkbook(stream))
                    {
                        var worksheet = workbook.Worksheet(1); // 获取第一个工作表
                        var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<WorkOrder> inventoriesList = new List<WorkOrder>();

                        foreach (var row in rows)
                        {



                            var inventory = new WorkOrder();
                           

                            inventory.WorkOrderCoding = row.Cell(1).GetValue<string>();
                            inventory.WorkOrderName = row.Cell(2).GetValue<string>();
                            inventory.WorkOrderType = row.Cell(3).GetValue<string>();
                            inventory.WorkorderSource = row.Cell(4).GetValue<string>();
                            inventory.OrderNumber = row.Cell(5).GetValue<string>();
                            inventory.ProductNumber = row.Cell(6).GetValue<string>();
                            inventory.ProductName = row.Cell(7).GetValue<string>();
                            inventory.Specifications = row.Cell(8).GetValue<string>();
                            inventory.Unit = row.Cell(9).GetValue<string>();
                            inventory.WorkOrderNum = row.Cell(10).GetValue<string>();
                            inventory.AdjustQuantity = row.Cell(11).GetValue<string>();
                            inventory.QuantityProduced = row.Cell(12).GetValue<string>();
                            inventory.LotNumber = row.Cell(13).GetValue<string>();
                            inventory.CustomerCode = row.Cell(14).GetValue<string>();
                            inventory.CustomerNamwe = row.Cell(15).GetValue<string>();
                            inventory.RequestDate = new DateTime();
                            inventory.State = row.Cell(17).GetValue<string>();
                            inventory.SupplierCode = row.Cell(18).GetValue<string>();
                            inventory.SupplierName = row.Cell(19).GetValue<string>();
                            inventory.Note = row.Cell(20).GetValue<string>();
                            inventoriesList.Add(inventory);

                        }





                        result.Code = APIEnum.添加成功;
                        result.Msg = "导入成功";
                        result.data = inventoriesList.Count;
                    }
                }
            }
            catch (Exception ex)
            {

                result.Code = APIEnum.添加失败;
                result.Msg = "导入失败，原因：" + ex.Message;
                return StatusCode(500, result);
            }
            return Ok(result);
        }
        
    }
}
